package com.gmss.crawler.task;


import com.alibaba.fastjson.*;
import com.gmss.crawler.module.company.service.*;
import com.gmss.crawler.module.integrity.integritycase.domain.*;
import com.gmss.crawler.module.integrity.integritycase.service.*;
import com.gmss.crawler.module.person.service.*;
import com.gmss.crawler.module.title.service.*;
import com.gmss.crawler.service.*;
import com.gmss.crawler.utils.*;
import lombok.extern.slf4j.*;
import org.apache.commons.collections4.*;
import org.apache.commons.lang3.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.util.*;
import java.util.concurrent.*;

@Slf4j
@Service
public class IntegrityCaseTask {

    @Resource
    private ICompanyService iCompanyService;
    @Resource
    private IPersonInfoService iPersonInfoService;
    @Resource
    private IPersonTitleService iPersonTitleService;
    @Resource
    private IIntegrityCaseService integrityCaseService;
    @Resource
    private IntegrityCaseCrawlerService integrityCaseCrawlerService;

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1024,
            1024, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1024), new ThreadPoolFactory("IntegrityCaseTask-data-task"));


    public void submit(JSONObject jsonObject) {
        threadPoolExecutor.submit(new SyncDataThread(jsonObject));
    }

    private class SyncDataThread implements Runnable {

        // 指定的日期
        private String fileName;
        private String filePath;
        private JSONObject jsonObject;

        public SyncDataThread(JSONObject jsonObject) {
            this.jsonObject = jsonObject;
        }

        @Override
        public void run() {
            try {
                if (jsonObject.containsKey("filePath") && StringUtils.isNotBlank(jsonObject.getString("filePath"))) {
                    filePath =jsonObject.getString("filePath");
                }
                if (jsonObject.containsKey("fileName") && StringUtils.isNotBlank(jsonObject.getString("fileName"))) {
                    fileName =jsonObject.getString("fileName");
                }
                List<IntegrityCase> integrityCaseList = integrityCaseCrawlerService.parseCase(jsonObject.getString("queryDateStr"));

                if (CollectionUtils.isNotEmpty(integrityCaseList) && !StringUtils.isAllBlank(fileName, filePath)) {
                    List<LinkedHashMap<String, Object>> list = convertExcel(integrityCaseList);
                    ExcelUtils.saveExcel(fileName, filePath, list);
                }



//                if (CollectionUtils.isNotEmpty(integrityCaseList)) {
//                    for (IntegrityCase integrityCase : integrityCaseList) {
//                        LambdaQueryWrapper<IntegrityCase> lambdaQueryWrapper = new LambdaQueryWrapper();
//                        lambdaQueryWrapper.eq(IntegrityCase::getTitle, integrityCase.getTitle());
//                        int count = integrityCaseService.count();
//                        if (count > 0)
//                            continue;
//                        integrityCaseService.save(integrityCase);
//                        List<PersonInfo> personInfoList = integrityCase.getPersonInfoList();
//                        if (CollectionUtils.isNotEmpty(personInfoList)) {
//                            for (PersonInfo personInfo : personInfoList) {
//                                iPersonInfoService.queryCompany(personInfo);
//                                personInfo.setCaseId(integrityCase.getId());
//                                personInfo.setAcademicianTitle(AcademicianEnum.RESEARCH_INTEGRITY.getCode());
//                                personInfo.setAcademicianTitleValue(AcademicianEnum.RESEARCH_INTEGRITY.getValue());
//                            }
//                            // 验证是否重名，并走保存或更新
//                            iPersonInfoService.verifyDuplicateNamesAndSaveOrUpdate(personInfoList);
//                        }
//                    }
//                } else {
//                    log.warn("科研诚信案件调查处理为空！查询日期：{}", DateUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
//                }
            } catch (Exception e) {
                log.info("IntegrityCaseTask异常： Exception:[{}]", e);
            }
        }

        private List<LinkedHashMap<String,Object>> convertExcel(List<IntegrityCase> integrityCaseList) {
            List<LinkedHashMap<String, Object>> rows = new ArrayList<>(integrityCaseList.size());
            Object object = integrityCaseList.get(0);
            if (object instanceof IntegrityCase) {
                List<IntegrityCase> list = (List<IntegrityCase>) integrityCaseList;
                list.forEach((IntegrityCase integrityCase) -> {
                    LinkedHashMap<String, Object> row = new LinkedHashMap<>(list.size());
                    row.put("唯一标识", "");
                    row.put("通报日期", integrityCase.getNotifyDate() != null ? DateUtils.dateToString(integrityCase.getNotifyDate(), "yyyy-MM-dd") : "");
                    row.put("第一作者", StringUtils.isNotBlank(integrityCase.getFirstAuthor()) ? integrityCase.getFirstAuthor() : "");
                    row.put("并列第一作者", StringUtils.isNotBlank(integrityCase.getAndFirstAuthor()) ? integrityCase.getAndFirstAuthor() : "");
                    row.put("通讯作者", StringUtils.isNotBlank(integrityCase.getFirstReportAuthor()) ? integrityCase.getFirstReportAuthor() : "");
                    row.put("第二作者", StringUtils.isNotBlank(integrityCase.getSecondAuthor()) ? integrityCase.getSecondAuthor() : "");
                    row.put("第三作者", StringUtils.isNotBlank(integrityCase.getThirdAuthor()) ? integrityCase.getThirdAuthor() : "");
                    row.put("第四作者", StringUtils.isNotBlank(integrityCase.getFourAuthor()) ? integrityCase.getFourAuthor() : "");
                    row.put("第五作者", StringUtils.isNotBlank(integrityCase.getFiveAuthor()) ? integrityCase.getFiveAuthor() : "");
                    row.put("第六作者", StringUtils.isNotBlank(integrityCase.getSixAuthor()) ? integrityCase.getSixAuthor() : "");
                    row.put("第七作者", StringUtils.isNotBlank(integrityCase.getSevenAuthor()) ? integrityCase.getSevenAuthor() : "");
                    row.put("第八作者", StringUtils.isNotBlank(integrityCase.getEightAuthor()) ? integrityCase.getEightAuthor() : "");
                    row.put("其他作者", StringUtils.isNotBlank(integrityCase.getOtherAuthor()) ? integrityCase.getOtherAuthor() : "");
//                    row.put("所在单位", CollectionUtils.isNotEmpty(integrityCase.getPersonInfoList()) ? integrityCase.getPersonInfoList().get(0).getWorkCompany() : "");
//                    row.put("单位所在地", CollectionUtils.isNotEmpty(integrityCase.getPersonInfoList()) ? integrityCase.getPersonInfoList().get(0).getCompanyAddress() : "");
//                    row.put("单位类型", CollectionUtils.isNotEmpty(integrityCase.getPersonInfoList()) ? integrityCase.getPersonInfoList().get(0).getCompanyType() : "");
                    row.put("论文", StringUtils.isNotBlank(integrityCase.getTitle()) ? integrityCase.getTitle() : "");
                    row.put("通报地址", StringUtils.isNoneBlank(integrityCase.getNotifyLink()) ? integrityCase.getNotifyLink() : "");
                    row.put("通报来源", StringUtils.isNotBlank(integrityCase.getNotifySource()) ? integrityCase.getNotifySource() : "");
                    row.put("处理结果", StringUtils.isNoneBlank(integrityCase.getHandleResult()) ? integrityCase.getHandleResult() : "");
                    rows.add(row);
                });
            }
            return rows;
        }
    }

    @PreDestroy
    public void destroy() {
        if (null != this.threadPoolExecutor) {
            this.threadPoolExecutor.shutdown();
        }
    }
}
